﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class PlayController : MonoBehaviour
{
    private Direction nextDirection = Direction.Up;

    private ManagerVars vars;
    private Vector3 nextPlatformPos;
    private Vector3 nextPlatformUpPos;
    private Vector3 nextPlatformLeftPos;
    private Vector3 nextPlatformDownPos;
    private Vector3 nextPlatformRightPos;

    private SpriteRenderer spr;
    private Sprite spFace;
    private Sprite spBack;

    private bool IsMoving = false;
    // Start is called before the first frame update
    void Awake()
    {
        vars = ManagerVars.GetManagerVars();
        EventCenter.AddListener<Direction>(EventDefine.Move, Move);
        spr = gameObject.GetComponent<SpriteRenderer>();
        spFace = vars.characterSpriteList[0];
        spBack = vars.characterSpriteList[1];
    }

    void Start()
    {

    }

    void OnDestroy()
    {
        EventCenter.RemoveListener<Direction>(EventDefine.Move, Move);
    }

    void Move(Direction direction)
    {
        if (!IsMoving)
        {
            IsMoving = true;
            this.nextDirection = direction;
            if (direction == Direction.Up)
            {
                spr.sprite = spBack;
                transform.localScale = Vector3.one;
                nextPlatformPos = nextPlatformUpPos;
            }
            else if (direction == Direction.Left)
            {
                spr.sprite = spBack;
                transform.localScale = new Vector3(-1, 1, 1);
                nextPlatformPos = nextPlatformLeftPos;
            }
            else if (direction == Direction.Down)
            {
                spr.sprite = spFace;
                transform.localScale = Vector3.one;
                nextPlatformPos = nextPlatformDownPos;
            }
            else if (direction == Direction.Right)
            {
                spr.sprite = spFace;
                transform.localScale = new Vector3(-1, 1, 1);
                nextPlatformPos = nextPlatformRightPos;
            }
            transform.DOMoveX(nextPlatformPos.x, 0.2f);
            transform.DOMoveY(nextPlatformPos.y + 0.7f, 0.15f);
        }

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Platform")
        {
            IsMoving = false;
            Vector3 currentPlatformPos = collision.gameObject.transform.position;
            nextPlatformLeftPos = new Vector3(currentPlatformPos.x - vars.nextXPox, currentPlatformPos.y + vars.nextYPox);
            nextPlatformUpPos = new Vector3(currentPlatformPos.x + 1 * vars.nextXPox, currentPlatformPos.y + 1 * vars.nextYPox);
            nextPlatformRightPos = new Vector3(currentPlatformPos.x + vars.nextXPox, currentPlatformPos.y - vars.nextYPox);
            nextPlatformDownPos = new Vector3(currentPlatformPos.x - 1 * vars.nextXPox, currentPlatformPos.y - 1 * vars.nextYPox);
        }
    }
}



